// pages/mine/mine.js
// 获取应用实例
var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
var appmine = getApp()
var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {

    flag: true,
    rotate: 0,
    name: '',
    distance: '***',
    scale: "11",
    open: false,
    points: [],
    rows: [],
    istoright: true,
    currentLatitude: '',
    currentLongitude: '',
    targetLatitude: '',
    targetLongitude: '',
    latitude: '21.109384',
    longitude: '110.490444',
    name: "",
    id1: "",
    name1: "",
    save_latitude: "",
    save_longitude: "",
    markers: [],
    inputModel: false,
    inputModel1: false,

  },


  //重命名收藏的地点(已完成)
  rename_OK: function () {
    // 点击确认发起请求修改名字
    var that = this
    wx.request({
      url: 'https://www.zhenfu.online/location',
      method: 'PUT',
      data: {
        id: that.data.id1,
        name: that.data.name1
      },
      success: (res) => {

        that.setData({
          inputModel1: false
        })
        // 提示
        wx.showToast({
          title: res.data.data,
          icon: 'success',
          duration: 2000
        })
        // 刷新收藏数据
        wx.request({
          url: 'https://www.zhenfu.online/location/list',
          method: 'GET',
          success: (res) => {
            console.log(res);
            this.setData({
              // 收藏地点数据数组
              //类型是名称和经纬度以及marker数组，使用callout
              markers: res.data.data,
              rows: res.data.data
            })
          }
        })

      }
    })
  },

  //重命名(已完成)
  rename_point: function (e) {
    // 根据id查取 ，名字回显
    var that = this
    wx.request({
      url: 'https://www.zhenfu.online/location/' + e.currentTarget.dataset.id,
      method: 'GET',
      success: (res) => {
        console.log("*************")
        console.log(res.data.data)
        that.setData({
          name1: res.data.data[0].name,
          id1: res.data.data[0].id
        })
      }
    })
    // 返回定位的主页
    if (this.data.open) {
      this.setData({
        open: false
      });
    } else {
      this.setData({
        open: true
      });
    }
    this.setData({
      inputModel1: true
    })
  },

  // 查询所有收藏(已完成)
  selectAll: function () {
    wx.request({
      url: 'https://www.zhenfu.online/location/list',
      method: 'GET',
      success: (res) => {
        console.log(res);
        this.setData({
          // 收藏地点数据数组
          //类型是名称和经纬度以及marker数组，使用callout
          markers: res.data.data,
          rows: res.data.data
        })
      }
    })
  },

  //选择收藏，查询单个point(已完成)
  select_point: function (e) {
    console.log(e.currentTarget.dataset.id)
    // 选择地点之后
    var that = this
    wx.request({
      url: 'https://www.zhenfu.online/location/' + e.currentTarget.dataset.id,
      method: 'GET',
      success: (res) => {
        console.log("======get======")
        console.log(res.data.data)
        console.log(res.data.data[0].latitude)
        console.log(res.data.data[0].longitude)
        this.setData({
          targetLatitude: res.data.data[0].latitude,
          targetLongitude: res.data.data[0].longitude,
          name: res.data.data[0].name
        })

        function location(latitude, longitude) {
          this.latitude = latitude;
          this.longitude = longitude;
        }
        //通过实例化来创建对象
        var location1 = new location(res.data.data[0].latitude, res.data.data[0].longitude)
        console.log(location1)
        that.setData({
          points: [location1],
          markers: res.data.data,
          flag: false
        })
        // 返回定位的主页
        if (this.data.open) {
          this.setData({
            open: false
          });
        } else {
          this.setData({
            open: true
          });
        }
        this.calculateDistanceFun();
      }
    })
  },

  // 计算两个经纬度的直线距离 https://lbs.qq.com/miniProgram/jsSdk/jsSdkGuide/methodCalculatedistance
  calculateDistanceFun() {
    var that = this
    const _onLocationChange = function (res) {
      wx.onLocationChange((res) => {
        // console.log("看一下res是什么")
        console.log(res)
        that.setData({
          currentLatitude: res.latitude,
          currentLongitude: res.longitude
        })
        qqmapsdk.calculateDistance({
          mode: 'straight', //直线距离
          // 起点坐标
          from: {
            latitude: that.data.currentLatitude,
            longitude: that.data.currentLongitude,
          },
          // 终点坐标 to是当前位置 注意是一个数组
          to: [{
            // 选择的地址目标
            latitude: that.data.targetLatitude,
            longitude: that.data.targetLongitude,
          }],
          success: (calc) => {
            // 计算结果输出为米
            let distance = calc.result.elements[0].distance;
            that.setData({
              distance: distance,
            })
            console.log(calc)
            console.log("计算距离为:", distance + '米');
          },
          // 失败的情况
          fail: (error) => {
            console.error('calculateDistance失败原因:', error);
          },
        })
      })
    }
    wx.startLocationUpdate({
      type: 'gcj02',
      success: (res) => {
        wx.onLocationChange(_onLocationChange)
      },
      fail: (error) => {
        console.log('startLocationUpdate失败原因:', error)
      }
    })
  },

  //停止导航
  stopNavigation: function () {
    this.setData({
      flag: true,
      name: '',
      distance: '',
    })
    wx.offLocationChange()
  },

  //删除收藏，删除后重新刷新地点的列表数据，查询所有points(已完成)
  delete_point: function (e) {
    console.log(e.currentTarget.dataset.id)
    var that = this
    // 根据id查询单个
    wx.request({
      url: 'https://www.zhenfu.online/location/' + e.currentTarget.dataset.id,
      method: 'GET',
      success: (res) => {
        console.log(res)
        var toast = "确定删除  " + res.data.data[0].name + "  地点吗？"
        console.log("打印toast")
        console.log(toast)
        wx.showModal({
          title: toast,
          success(res) {
            if (res.confirm) {
              // 用户点击确定，根据id发起请求删除position
              wx.request({
                url: 'https://www.zhenfu.online/location/' + e.currentTarget.dataset.id,
                method: 'DELETE',
                success: (res) => {
                  console.log("===============================")
                  console.log(res)
                  wx.showToast({
                    title: res.data.data,
                    icon: 'success',
                    duration: 1500
                  })
                  // 刷新收藏地点数组数据
                  wx.request({
                    url: 'https://www.zhenfu.online/location/list',
                    method: 'GET',
                    success: (res) => {
                      console.log(res);
                      that.setData({
                        rows: res.data.data,
                        markers: res.data.data,
                      })
                    }
                  })
                }
              })
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    })

  },

  // 操作收藏(已完成)
  tap_ch: function (e) {

    wx.request({
      url: 'https://www.zhenfu.online/location/list',
      method: 'GET',
      success: (res) => {
        console.log(res);
        this.setData({
          // 收藏地点数据数组
          //类型是名称和经纬度以及marker数组，使用callout
          markers: res.data.data,
          rows: res.data.data
        })
      }
    })

    if (this.data.open) {
      this.setData({
        open: false
      });
    } else {
      this.setData({
        open: true
      });
    }
  },

  // 点击空白处返回(已完成)
  tap_end: function (e) {
    if (this.istoright) {
      this.setData({
        open: true
      });
    } else {
      this.setData({
        open: false
      });
    }
  },

  // 回到自己定位点(已完成)
  goBack: function clickcontrol(e) {
    let mpCtx = wx.createMapContext("map")
    mpCtx.moveToLocation()
  },

  //提示框确定(已完成)
  handlestoreCodeOK: function () {

    var that = this
    //判断name值是否为空
    if (that.data.name == "") {
      wx.showToast({
        title: '输入名称！',
        icon: 'error',
        duration: 3000
      })
      // name为空重置
      that.data.save_latitude = ""
      that.data.save_longitude = ""
      return
    }
    // 获取当前的经纬度
    wx.getLocation({
      altitude: true,
      type: 'gcj02',
      success(res) {
        that.data.save_latitude = res.latitude
        that.data.save_longitude = res.longitude
        console.log(res)
        //请求服务器保存收藏的地点
        // 把定义的名称传过去
        wx.request({
          url: 'https://www.zhenfu.online/location/save',
          method: 'POST',
          data: {
            latitude: that.data.save_latitude,
            longitude: that.data.save_longitude,
            name: that.data.name,
          },
          success: (res) => {
            // 清除name
            that.setData({
              name: ""
            })

            console.log(res);
            // 提示
            wx.showToast({
              title: res.data.data,
              icon: 'success',
              duration: 2000
            })
            //收藏成功后，刷新收藏地点数据
            wx.request({
              url: 'https://www.zhenfu.online/location/list',
              method: 'GET',
              success: (res) => {
                console.log(res);
                that.setData({
                  // 收藏地点数据数组
                  //类型是名称和经纬度以及marker数组，使用callout
                  markers: res.data.data,
                  rows: res.data.data
                })
              }
            })

          }
        })
      }
    })
    this.setData({
      inputModel: false
    })
  },

  //提示框取消(已完成)
  handlestoreCodeNo1: function () {
    this.setData({
      inputModel1: false
    })

  },
  //提示框取消(已完成)
  handlestoreCodeNo: function () {
    this.setData({
      inputModel: false
    })

  },
  // 点击收藏（已完成）
  startPosition: function () {

    this.setData({
      inputModel: true
    })
  },

  //（已完成）
  onLoad(options) {
    var that = this
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'MA2BZ-UI6KM-NJD62-6YX4C-O22M6-HQBD6'
    });
    // 页面加载收藏地点的数据
    wx.request({
      url: 'https://www.zhenfu.online/location/list',
      method: 'GET',
      success: (res) => {
        console.log(res);
        this.setData({
          // 收藏地点数据数组
          //类型是名称和经纬度以及marker数组，使用callout
          markers: res.data.data,
          rows: res.data.data
        })
      }
    })


  },

})